import axios from 'axios'
import QS from 'qs'
import { setSessionTicket, getSessionTicket } from '@/plugins/auth'

let getSessionTicketTimes = 0 // sessionticket 请求次数
let gettingSessionTicket = false
// let sessionTicket = getSessionTicket() || ''

axios.defaults.timeout = 5000

// 环境的切换
if (process.env.NODE_ENV == 'development') {
    axios.defaults.baseURL = '//gt4api.wxhand.com'
} else if (process.env.NODE_ENV == 'production') {
    axios.defaults.baseURL = '//mp-api.zsdx.cn'
    // axios.defaults.baseURL = '//gt4api.wxhand.com'
}

// 请求拦截 可在请求头中加入token等
axios.interceptors.request.use(
    (config) => {
        config.headers['zsdx-session-ticket'] = getSessionTicket()

        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

/**
 * 远程请求sessionticket
 */
export function createSessionTicket() {
    console.log(getSessionTicketTimes, 'time')
    return new Promise((resolve, reject) => {
        if (getSessionTicketTimes > 3) {
            reject(new Error('服务器错误，请稍后重试'))
        }
        gettingSessionTicket = true

        axios
            .get('/hire/Basic/createSessionTicket')
            .then(function(resp) {
                if (resp.data.code === 1) {
                    setSessionTicket(resp.data.data.session_ticket)

                    // if (!process.server) {
                    //     document.cookie =
                    //         'zdSessionTicket=' +
                    //         resp.data.data.session_ticket +
                    //         ';path=/'
                    //     localStorage.sessionTicket = resp.data.session_ticket
                    // }
                } else {
                    console.log('获取sessionTicket失败')
                }
                gettingSessionTicket = false
                getSessionTicketTimes++
                resolve(resp.data.data.session_ticket)
            })
            .catch(function(err) {
                gettingSessionTicket = false
                getSessionTicketTimes++
                // 并未超出次数, 稍后重试
                resolve(err)
            })
    })
}

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params) {
    return new Promise((resolve, reject) => {
        axios
            .get(url, {
                params
            })
            .then((res) => {
                resolve(res.data)
            })
            .catch((err) => {
                reject(err.data)
            })
    })
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */

export function post(url, params) {
    return new Promise((resolve, reject) => {
        if (gettingSessionTicket) {
            setTimeout(function() {
                post(url, params)
                    .then((resp) => resolve(resp))
                    .catch((resp) => reject(resp))
            }, 200)
            return
        }
        if (!getSessionTicket()) {
            createSessionTicket()
                .then(() => {
                    post(url, QS.stringify(params))
                        .then((resp) => resolve(resp))
                        .catch((resp) => reject(resp))
                })
                .catch((err) => {
                    console.log(err)
                })
        } else {
            axios
                .post(url, QS.stringify(params))
                .then((resp) => {
                    if (resp.data.code == 1001) {
                        // 重新获取sessionTicket
                        if (gettingSessionTicket) {
                            setTimeout(function() {
                                post(url, params)
                                    .then((resp) => resolve(resp.data))
                                    .catch((resp) => reject(resp))
                            }, 200)
                        } else {
                            createSessionTicket()
                                .then((res) => {
                                    post(url, params)
                                        .then((resp) => resolve(resp.data))
                                        .catch((resp) => reject(resp))
                                })
                                .catch((error) => {
                                    resolve({
                                        code: -999,
                                        msg:
                                            url +
                                            'axios请求错误,重新获取ticket:' +
                                            error
                                    })
                                })
                        }
                    } else if (resp.code == 1002) {
                        console.log('1002')
                        // TODO 添加登录方法, 前后端均需处理
                        // if (!params.no_login) {
                        //     this.$store.commit('isLogin/SHOW_LOGIN', {
                        //         type: 'login'
                        //     })
                        // }
                        reject(new Error('需要登录'))
                    } else {
                        resolve(resp.data)
                    }
                })
                .catch((err) => {
                    reject(err.data)
                })
        }
    })
}
